package org.goodev.arch;

import android.annotation.SuppressLint;
import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;

// 实现 LifecycleObserver 表明希望监听生命周期时间，
public class LocationMgr implements LifecycleObserver {
    private final Context mContext;
    private final LocationListener mListener;
    private LocationManager mLocationManager;
    private Lifecycle mLifecycle;
    private boolean mEnabled = false;
    public LocationMgr(Lifecycle lifecycle, LocationListener listener, Context context) {
        mLifecycle = lifecycle;
        mContext = context;
        mListener = listener;
    }

    @SuppressLint("MissingPermission")
    // 通过注解来告诉 Observer 监听的事件
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    public void addLocationListener() {
        if (mEnabled) {
            listen();
        }
    }

    // 添加一个启用监听位置更新的功能，当条件满足的时候，调用该函数来开始监听位置
    public void enable() {
        if (mEnabled) {
            return;
        }
        mEnabled = true;
        if (mLifecycle.getCurrentState().isAtLeast(Lifecycle.State.RESUMED)) {
            listen();
        }
    }

    private void listen() {
        if (mLocationManager == null) {
            // 已经在监听了
            return;
        }
        mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 0, mListener);
        // Force an update with the last location, if available.
        Location lastLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (lastLocation != null) {
            mListener.onLocationChanged(lastLocation);
        }
    }

    // 通过注解来告诉 Observer 监听的事件
    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    void removeLocationListener() {
        if (mLocationManager == null) {
            return;
        }
        mLocationManager.removeUpdates(mListener);
        mLocationManager = null;
    }
}
